package com.kun.demo01;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.net.URL;
import java.util.concurrent.*;

//测试线程创建，下载网络图片
public class ThreadCreate03_test implements Callable<Boolean> {

    String url;
    String fileName;

    public Boolean call(){
        this.downloadPicture(url, fileName);
        return true;
    }

    public void downloadPicture(String url, String fileName){
        try {
            FileUtils.copyURLToFile(new URL(url), new File(fileName));
            System.out.println("下载图片成功："+fileName);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("下载图片失败");
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1. 创建线程对象
        ThreadCreate03_test test1 = new ThreadCreate03_test();
        test1.url = "https://www.baidu.com/img/bd_logo1.png";
        test1.fileName = "baidu_1.png";
        ThreadCreate03_test test2 = new ThreadCreate03_test();
        test2.url = "https://www.baidu.com/img/bd_logo1.png";
        test2.fileName = "baidu_2.png";
        ThreadCreate03_test test3 = new ThreadCreate03_test();
        test3.url = "https://www.baidu.com/img/bd_logo1.png";
        test3.fileName = "baidu_3.png";

        //2. 创建目标服务--线程池
        ExecutorService executor = Executors.newFixedThreadPool(3);
        //3. 提交任务，获取返回结果
        Future<Boolean> res1 = executor.submit(test1);
        Future<Boolean> res2 = executor.submit(test2);
        Future<Boolean> res3 = executor.submit(test3);
        System.out.println("图片1下载结果:"+res1.get());
        System.out.println("图片2下载结果:"+res2.get());
        System.out.println("图片3下载结果:"+res3.get());
        //4. 关闭线程池
        executor.shutdown();

        System.out.println("下载图片结束");
    }
}
